package com.niiwoo.civet.trade.listener;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.constant.MQConstant;
import com.niiwoo.civet.account.dto.request.TransFreezeRequestDTO;
import com.niiwoo.civet.trade.constant.TradeMqConstant;
import com.niiwoo.civet.trade.dto.newRefund.PenaltyUpdaterDTO;
import com.niiwoo.civet.trade.service.local.newRefund.penalty.PenaltyHandlerJobService;
import com.niiwoo.civet.trade.service.local.newRefund.refundDeal.RefundForRepaymentService;
import com.niiwoo.civet.trade.service.local.newRefund.refundDeal.core.RefundDetailHandlerService;
import com.niiwoo.tripod.provider.exception.BizException;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class RepaymentListener {
    @Autowired
    private PenaltyHandlerJobService penaltyHandlerJobService;
    @Autowired
    private RefundDetailHandlerService refundDetailHandlerService;
    @Autowired
    private RefundForRepaymentService refundForRepaymentService;
    /**
     * 罚息更新监听者
     * @param penaltyUpdaterDTO
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = {TradeMqConstant.AUTO_PENALTY_UPDATE_QUEUE})
    public void calcPenaltyForProjectForJobComsumer(PenaltyUpdaterDTO penaltyUpdaterDTO, Message message, Channel channel) throws IOException {
        if (penaltyUpdaterDTO == null){
            return;
        }
        try {
            penaltyHandlerJobService.calcPenaltyForProjectForJobComsumer(penaltyUpdaterDTO.getProjectId(),penaltyUpdaterDTO.getCurrentDate(),penaltyUpdaterDTO.getStep());
        } catch (Exception e) {
            log.error("autoPenaltyUpdate exception,标的号{}",penaltyUpdaterDTO.getProjectId());
        }finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

    /**
     * 还款订单消费才
     * @param refundOrderId
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = {TradeMqConstant.REFUND_ORDER_DETAIL_HANLDER_QUEUE})
    public void refundOrderHandlerComsumer(Long refundOrderId, Message message, Channel channel) throws IOException {
        log.info("refundOrderHandlerComsumer.init--refundOrderId={}",refundOrderId);
        if (refundOrderId == null){
            return;
        }
        try {
            refundDetailHandlerService.handleOneRefundOrder(refundOrderId,false);
        } catch (Exception e) {
            log.error("处理还款订单失败,refundOrderId={}",refundOrderId, e);
        }finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

    /**
     * 还款发起时校验债权关系
     * @param transFreezeRequestDTO
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = {MQConstant.REFUND_VALIDATE_QUEUE})
    public void refundValidateDebt(TransFreezeRequestDTO transFreezeRequestDTO, Message message, Channel channel) throws IOException {
        boolean isAck = true;//应答
        if (transFreezeRequestDTO == null){
            return;
        }
        try {
            refundForRepaymentService.freezeWithValidateDebt(transFreezeRequestDTO);
        } catch (Exception e) {
            if (e instanceof BizException) {
                log.info("处理还款订单失败,transFreezeRequestDTO={},error={},msg={}", JSON.toJSONString(transFreezeRequestDTO),((BizException) e).getErrorCode(),e.getMessage());
                //重新发送
                isAck = false;
                try {
                    Thread.sleep(6 * 1000L);
                } catch (InterruptedException e1) {
                    log.error("refundValidateDebt sleep error");
                }
            }else {
                log.error("还款refundValidateDebt异常,transFreezeRequestDTO={}", JSON.toJSONString(transFreezeRequestDTO),e);
            }
        }finally {
            if (isAck){
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }
}
